/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.controller;

import com.alibaba.fastjson.JSON;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.purpose.bean.SafetyActivityLedgerBean;
import com.koron.purpose.bean.SafetyActivityPersonBean;
import com.koron.purpose.service.api.SafetyActivityService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "safetyActivity", description = "安全活动台账")
@RestController
@RequestMapping("/safetyActivity")
public class SafetyActivityController {
    private final static  Logger logger = LoggerFactory.getLogger(SafetyActivityController.class);

    @Autowired
    private SafetyActivityService safetyActivityService;

    @ApiOperation("查询活动台账列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wcorpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityType", value = "活动类型",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpName", value = "公司",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "departmentName", value = "部门名称",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "活动时间开始(时间格式：yyyy-MM-dd HH:mm:ss)",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "stopTime", value = "活动时间结束(时间格式：yyyy-MM-dd HH:mm:ss)",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页",  dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数",  dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/querySafetyActivityLedgers.htm", method = RequestMethod.GET)
    public MessageBean<?> querySafetyActivityLedgers(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String wcorpCode, @ApiIgnore String activityType, @ApiIgnore String corpName,
                                                     @ApiIgnore String departmentName, @ApiIgnore String startTime, @ApiIgnore String stopTime,
                                                     @ApiIgnore Integer page, @ApiIgnore Integer pageSize) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
        MessageBean<DataBean<Map>> msg;
        msg = safetyActivityService.querySafetyActivityLedgers(wcorpCode, activityType, corpName, departmentName, startTime, stopTime, page, pageSize);
        return msg;
    }

    @ApiOperation("根据ID查询安全活动台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/queryById.htm", method = RequestMethod.GET)
    public MessageBean<?> queryById(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String id) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return safetyActivityService.queryById(id);
    }

    @ApiOperation("新增安全活动台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wcorpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "wcorpName", value = "水司名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityName", value = "活动名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityType", value = "活动类型code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityTypeName", value = "活动类型", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityPrincipal", value = "活动负责人code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityPrincipalName", value = "活动负责人", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpName", value = "公司名称",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "departmentCode", value = "部门code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "departmentName", value = "部门名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间(时间格式：yyyy-MM-dd HH:mm:ss)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "stopTime", value = "结束时间(时间格式：yyyy-MM-dd HH:mm:ss)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityObjective", value = "活动目的",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityRecord", value = "活动记录",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activitySummary", value = "活动总结",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "remark", value = "备注",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "personBeans", value = "活动人员(JSON数组,如[{'personCode':'人员code','personName':'人员姓名'," +
                    "'deparCode':'部门code','deparName':'部门名称'," +
                    "'corpCode':'公司code','corpName':'公司名称'," +
                    "'awardedMarks':'加分(Integer)','remark':'备注'}] )",  paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/insertSafetyActLedg.htm", method = RequestMethod.POST)
    @Log(title = "新增安全活动台账", businessModule = "安全文化", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> insertSafetyActLedg(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                              @ApiIgnore SafetyActivityLedgerBean bean,
                                              @ApiIgnore String personBeans, @RequestParam(value = "files", required = false) MultipartFile[] files) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        List<SafetyActivityPersonBean> list = null;
        if (!StringUtils.isEmpty(personBeans)) {
            list = JSON.parseArray(personBeans, SafetyActivityPersonBean.class);
        }
        return safetyActivityService.insertSafetyActLedg(bean, user, list, files);
    }

    @ApiOperation("删除安全活动台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/deleteSafetyActLedg.htm", method = RequestMethod.POST)
    @Log(title = "删除安全活动台账",businessModule = "安全文化", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<?> deleteSafetyActivity(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String id) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return safetyActivityService.deleteSafetyActivity(id);
    }

    @ApiOperation("修改安全活动台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityName", value = "活动名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityType", value = "活动类型", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityTypeName", value = "活动类型", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityPrincipal", value = "活动负责人code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityPrincipalName", value = "活动负责人", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpName", value = "公司名称",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "departmentCode", value = "部门code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "departmentName", value = "部门名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间(时间格式：yyyy-MM-dd HH:mm:ss)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "stopTime", value = "结束时间(时间格式：yyyy-MM-dd HH:mm:ss)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityObjective", value = "活动目的",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityRecord", value = "活动记录",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activitySummary", value = "活动总结",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "remark", value = "备注",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "personBeans", value = "活动人员(JSON数组,如[{'id':'人员记录id(如果id不存在，为新增)','personCode':'人员code','personName':'人员姓名'," +
                    "'deparCode':'部门code','deparName':'部门名称'," +
                    "'corpCode':'公司code','corpName':'公司名称'," +
                    "'awardedMarks':'加分(Integer)','remark':'备注'}] )",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityAccessory", value = "活动附件(参数格式为JSON字符串，" +
                    "如( [{'filename':'xxx','fileUrl':'xxx'},{'filename':'xxx','fileUrl':'xxx'}] ))",  paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/updateSafetyActivity.htm", method = RequestMethod.POST)
    @Log(title = "修改安全活动台账",businessModule = "安全文化", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean updateSafetyActivity(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                            @ApiIgnore SafetyActivityLedgerBean bean, @ApiIgnore String activityAccessory,
                                            @ApiIgnore String personBeans, @RequestParam(value = "files", required = false) MultipartFile[] files) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        List<SafetyActivityPersonBean> list = null;
        if (!StringUtils.isEmpty(personBeans)) {
            list = JSON.parseArray(personBeans, SafetyActivityPersonBean.class);
        }
        return safetyActivityService.updateSafetyActivity(user, bean, activityAccessory, list, files);
    }

    @ApiOperation("导出安全活动台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wcorpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "activityType", value = "活动类型",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpName", value = "公司",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "departmentName", value = "部门名称",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "活动时间开始(时间格式：yyyy-MM-dd HH:mm:ss)",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "stopTime", value = "活动时间结束(时间格式：yyyy-MM-dd HH:mm:ss)",  paramType = "query", dataType = "String"),
    })
    @RequestMapping(value = "/exportSafetyActivity.htm", method = RequestMethod.GET)
    @Log(title = "导出安全活动台账",businessModule = "安全文化", businessManipulation = BusinessManipulation.EXPORT)
    public HttpEntity<?> exportSafetyActivity(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String wcorpCode, @ApiIgnore String activityType, @ApiIgnore String corpName,
                                              @ApiIgnore String departmentName, @ApiIgnore String startTime, @ApiIgnore String stopTime) {
        if (null == user) {
            return null;
        }
        List<Map> list = safetyActivityService.querySafetyActivityLedgers(wcorpCode, activityType, corpName, departmentName, startTime, stopTime);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File file = new File("static/excel/SafetyActivityExport.xlsx");
        try (
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/excel/SafetyActivityExport.xlsx");
        ) {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("安全活动台账", file, "SafetyActivityExport.btl", map);
    }

    @ApiOperation(value = "下载安全活动台账excel模板")
    @RequestMapping(value = "/downloadtemplate.htm", method = {RequestMethod.GET})
    public HttpEntity<?> downloadTemplate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        File targetFile = new File("static/excel/SafetyActivityMsg.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/SafetyActivityExcel.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("安全活动台账模板", targetFile, "default.btl", map);
    }
}
